﻿import com.dinmax.flash.utilities.movieclip.*

class MovieHelper {
	
	public static function interpolate(clip, prop, nInit, nEnd, nRatio, fListener, root:MovieClip):MovieClip {
		
		var controller;
		(root) ? controller = DummyFactory.getNextDummy(root) : controller = DummyFactory.getNextDummy(clip);
		
		var nCount = 0;
		var nLastDif;
		
		var isPositive:Boolean = nEnd > clip[prop];
		
		clip[prop] = nInit;
		
		controller.onEnterFrame = function(){
					
			if(isPositive){
				var nDif:Number = nEnd - clip[prop];
			} else {
				var nDif:Number = clip[prop] - nEnd;
			}
			
			if(nDif < 2 || nDif == nLastDif) {
				nCount++;
			}
			
			if(nDif < 0.8 || nCount > 15){
				delete this.onEnterFrame;
				clip[prop] = nEnd;
				fListener(clip, prop);
				this.removeMovieClip();
				
			} else {
				if(isPositive){
					clip[prop] += nDif / nRatio;
				} else {
					clip[prop] -= nDif / nRatio;
				}
			}
			
			nLastDif = nDif;
		}
		
		controller.stopInterpolation = function(){
			delete this.onEnterFrame;
			this.removeMovieClip();
		}
		
		return controller;
	}
	
	public static function watchTimeLine(clip:MovieClip, percent:Number, fListener):MovieClip {
		
		var controller = DummyFactory.getNextDummy();
		
		var total:Number = clip._totalframes;
		var nFrame:Number = percent * total / 100;
		
		controller.onEnterFrame = function(){
			if(clip._currentframe >= nFrame){
				delete this.onEnterFrame;
				
				fListener(clip, percent);
				this.removeMovieClip();
			}
		}
		
		controller.stopWatcher = function(){
			delete this.onEnterFrame;
			this.removeMovieClip();
		}
		
		return controller;
	}
	
	public static function timer(nTime:Number, milliseconds:Boolean, fListener):MovieClip {
		var controller:MovieClip = DummyFactory.getNextDummy();
		
		var nTimer:Number = getTimer();
		var nCount:Number = 0;
		
		controller.onEnterFrame = function(){
			if((milliseconds && getTimer() - nTimer > milliseconds) || nCount > nTime){
				delete this.onEnterFrame;
				fListener();
				this.removeMovieClip();
				
			} else if(!milliseconds) {
				nCount++;
			}
		}
		
		controller.stopTimer = function(){
			delete this.onEnterFrame;
			this.removeMovieClip();
		}
		
		return controller;
	}
	
	public static function rewind(clip, fListener):MovieClip {
		var controller:MovieClip = DummyFactory.getNextDummy();
		
		controller.onEnterFrame = function(){
			if(clip._currentframe == 1){
				delete this.onEnterFrame;
				fListener();
				this.removeMovieClip();
				
			} else {
				clip.prevFrame();
			}
		}
		
		controller.stopRewind = function(){
			delete this.onEnterFrame;
			this.removeMovieClip();
		}
		
		return controller;
	}
	
}